package cn.edu.hbwe.book.dao;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import cn.edu.hbwe.book.entity.Book;
import cn.edu.hbwe.book.util.DBUtil;

public class Bookdao {
	  
		public void add(Book Book) {
			
			QueryRunner run=new  QueryRunner(); //创建QueryRunner对象
			
			Connection conn=DBUtil.getConn();// 连接数据库
			try {
				
				//System.out.println("数据库连接成功！");
				String sql = "insert into Book(id, username, password, email) values(?, ?, ?, ?)";
				
				run.update(conn, sql, Book.getId(),Book.getName());
				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally {
				DBUtil.getConn();
			}
			
		}

		public void update(Book Book) {

			QueryRunner run=new  QueryRunner();
			
			Connection conn=DBUtil.getConn();
			try {
				
				//System.out.println("数据库连接成功！");
				String sql = "update Book set username=?,password=?,email=? where id=?";
				
				run.update(conn, sql,Book.getName(),Book.getId());
				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally {
				DBUtil.getConn();
			}
		}

		public void delete(String id) {
			
			QueryRunner run=new  QueryRunner();
			Connection conn=DBUtil.getConn();		
			try {
				
				//System.out.println("数据库连接成功！");
				String sql = "delete from Book where id=?";
				
				run.update(conn, sql, id);
				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally {
				DBUtil.getConn();
			}
			
		}
		
		public Book findById(String id) {
			Book Book = null;
			
			QueryRunner run=new QueryRunner();
				
			ResultSetHandler<Book> h=new BeanHandler<Book>(Book.class);
			Connection conn=DBUtil.getConn();
			
			try {			
				String sql = "select * from Book where id = ?";
				
				Book=run.query(conn, sql, h, id);
				
			} catch (Exception e) {
				e.printStackTrace();
			}finally {
				DBUtil.getConn();
			}
			return Book;
		}
		
		public List<Book> findAll(){
			List<Book> Books = new ArrayList<Book>();
			
			QueryRunner run=new QueryRunner();
			
			ResultSetHandler<List<Book>> h=new BeanListHandler<Book>(Book.class);
			Connection conn=DBUtil.getConn();
			
			try {
				
				String sql = "select * from Book ";
				
				Books=run.query(conn, sql, h);
				
			}catch(Exception e){
				e.printStackTrace();
			}finally {
				DBUtil.getConn();
			}
			return Books;
		}
	
}
